package com.andnnl.springbootdemo.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by chenss on 2019/3/1.
 */
public class JsonBuilder {

    ObjectMapper mapper = new ObjectMapper();

    Map<String, Object> map;

    private JsonBuilder() {
        map = new HashMap<>();
    }

    public static JsonBuilder builder() {
        return new JsonBuilder();
    }

    public static JsonBuilder builder(String key, Object obj) {
        return builder().put(key, obj);
    }

    public JsonBuilder put(String key, Object obj) {
        this.map.put(key, obj);
        return this;
    }

    public String build() {
        try {
            return mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public Map<String, Object> buildMap() {
       return map;
    }
}
